"""
一键启动脚本 - 同时启动 MCP 服务器和 FastAPI 应用
"""
import multiprocessing
import sys
import time
import signal
from pathlib import Path

# 添加当前目录到路径
sys.path.insert(0, str(Path(__file__).parent))

# --- 服务配置 ---
MCP_PORT = 7888
FASTAPI_PORT = 8000
MCP_URL = f"http://localhost:{MCP_PORT}/mcp"
FASTAPI_URL = f"http://localhost:{FASTAPI_PORT}"
CHAT_URL = f"http://localhost:{FASTAPI_PORT}/chat/stream"

def run_mcp_server():
    """运行 MCP 服务器"""
    try:
        from multy_server import run_mcp_server as start_mcp
        start_mcp(port=MCP_PORT)
    except Exception as e:
        print(f"❌ MCP 服务器启动失败: {e}", file=sys.stderr)
        sys.exit(1)

def run_fastapi():
    """运行 FastAPI 应用"""
    try:
        import uvicorn
        import asyncio
        from Langchin_mcp import app, initialize_agent
        
        asyncio.run(initialize_agent())
        uvicorn.run(app, host="0.0.0.0", port=FASTAPI_PORT)
    except Exception as e:
        print(f"❌ FastAPI 应用启动失败: {e}", file=sys.stderr)
        sys.exit(1)

def main():
    """主函数"""
    # Windows 系统必须设置启动方法为 'spawn'
    if sys.platform == "win32":
        multiprocessing.set_start_method("spawn", force=True)

    # 注册信号处理器，用于优雅退出
    def signal_handler(sig, frame):
        print("\n🛑 正在停止所有服务...")
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    if hasattr(signal, 'SIGTERM'):
        signal.signal(signal.SIGTERM, signal_handler)

    print("🚀 启动 MCP AI Server...")
    print(f"   - MCP 服务器: {MCP_URL}")
    print(f"   - FastAPI 应用: {FASTAPI_URL}")
    print(f"   - 聊天接口: {CHAT_URL}\n")

    processes = []
    try:
        # 创建并启动 MCP 服务器进程
        p_mcp = multiprocessing.Process(target=run_mcp_server, name="MCP-Server")
        p_mcp.start()
        processes.append(p_mcp)
        time.sleep(2) # 等待启动

        if not p_mcp.is_alive():
            print("❌ MCP 服务器启动失败。")
            sys.exit(1)
        print("✅ MCP 服务器已启动")

        # 创建并启动 FastAPI 应用进程
        p_fastapi = multiprocessing.Process(target=run_fastapi, name="FastAPI-App")
        p_fastapi.start()
        processes.append(p_fastapi)
        time.sleep(2) # 等待启动

        if not p_fastapi.is_alive():
            print("❌ FastAPI 应用启动失败。")
            sys.exit(1)
        print("✅ FastAPI 应用已启动")

        print("\n✅ 所有服务已启动成功！按 CTRL+C 停止。\n")

        # 主循环：监控子进程状态
        while True:
            for p in processes:
                if not p.is_alive():
                    print(f"❌ 进程 {p.name} 意外退出。")
                    sys.exit(1)
            time.sleep(1)

    except KeyboardInterrupt:
        print("\n🛑 收到停止信号，正在关闭...")
    finally:
        # 确保所有子进程都被终止
        for p in processes:
            if p.is_alive():
                p.terminate()
                p.join(timeout=3)
                if p.is_alive():
                    p.kill()
        print("✅ 所有服务已停止。")

if __name__ == "__main__":
    main()
